import React, { Component } from 'react'
import { getRes } from "../../../../configFile";
import DataCategory from "../../../../types/DataCategory";
import { FormInstance } from "antd/lib/form";
import DataType from "../../../../types/DataType";
import { Button, Card, Form, Input, Spin, Radio, message, Space } from "antd";
import { Store, ValidateErrorEntity } from "rc-field-form/lib/interface";
import { addDataCategory } from "../../../../requests/DataCategory";
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import './AddDataCategory.less'

interface IProps { }
interface IState {
    dataCategory: DataCategory
    isLoading: boolean
    selectValue: string
    optionNumber: number
}

export default class AddDataCategory extends Component<IProps, IState> {
    formRef = React.createRef<FormInstance>()
    constructor(props: IProps) {
        super(props)
        this.state = {
            isLoading: true,
            dataCategory: {
                dataCategoryID: -1,
                dataCategoryName: '',
                dataType: DataType.TEXT
            },
            selectValue: '',
            optionNumber: 0
        }
    }

    layout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 },
    };

    tailLayout = {
        wrapperCol: { offset: 4, span: 16 },
    };

    async componentDidMount() {
        this.setState({
            ...this.state,
            isLoading: false,
        })
    }

    //输入的数据类型改变
    onDataTypeChange = (e: any) => {
        console.log('radio checked', e.target.value);
        this.setState({
            ...this.state,
            selectValue: e.target.value,
        });
    };

    //输入合法函数
    onFinish: (values: Store) => void = async values => {
        console.log(values)
        try {
            //选择类型没有加入选项
            if (this.state.selectValue === DataType.SELECT && this.state.optionNumber === 0) {
                message.error("未加入选项")
                return;
            }
            this.setState({ isLoading: true })
            const res = getRes(await addDataCategory(values.dataCategoryName, values.dataType, values.selectList?.map((item: { selectList: string }) => item.selectList)))
            if (res.isSuccessful === true) {
                message.success("添加成功")
            } else {
                console.error(res);
                message.error("添加失败")
            }
        } catch (err) {
            message.error(err.toString())
        } finally {
            this.setState({
                ...this.state,
                isLoading: false
            })
        }
    }

    onFinishFailed = (errorInfo: ValidateErrorEntity) => {
        message.error(errorInfo.errorFields[0].errors[0]);
    };

    normFile = (e: { fileList: any; }) => {
        console.log('Upload event:', e);
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };

    render() {
        return (
            <div>
                <Spin size='large' spinning={this.state.isLoading}>
                    <Card
                        title={<span style={{ fontWeight: 'bold' }}>添加数据类型</span>}
                        bordered={true}>
                        <Form
                            onFinishFailed={this.onFinishFailed}
                            onFinish={this.onFinish}
                            ref={this.formRef}
                            {...this.layout}
                            name="addDataCategory"
                        >

                            <Form.Item
                                label="数据类型名"
                                name="dataCategoryName"
                                rules={[{ required: true }]}
                            >
                                <Input />
                            </Form.Item>

                            <Form.Item
                                label="数据类型"
                                name="dataType"
                                rules={[{ required: true }]}
                            >
                                <Radio.Group onChange={this.onDataTypeChange} value={this.state.selectValue}>
                                    <Radio value={DataType.SELECT}>选择类型</Radio>
                                    <Radio value={DataType.TEXT}>文本类型</Radio>
                                    <Radio value={DataType.TWODIMENSIONAL}>二维数据</Radio>
                                </Radio.Group>
                            </Form.Item>

                            <Form.List name="selectList">
                                {(fields, { add, remove }) => {
                                    //选择下才显示
                                    if (this.state.selectValue === DataType.SELECT)
                                        return (
                                            <div>
                                                {
                                                    fields.map((field, index) => (
                                                        <Form.Item
                                                            {...(index === 0 ? { ...this.layout } : { ...this.tailLayout })}
                                                            label={index === 0 ? '选项' : ''}
                                                            required={false}
                                                            key={field.key}
                                                        >
                                                            <Space style={{ alignItems: 'start' }}>
                                                                <Form.Item
                                                                    name={[field.name, 'selectList']}
                                                                    rules={[{ required: true, message: '选项不可省略' }]}
                                                                >
                                                                    <Input placeholder="请输入选项或删除该选项" />
                                                                </Form.Item>

                                                                <MinusCircleOutlined
                                                                    style={{ fontSize: '32px' }}
                                                                    onClick={() => {
                                                                        remove(field.name);
                                                                    }}
                                                                />
                                                            </Space>
                                                        </Form.Item>
                                                    ))}
                                                <Form.Item
                                                    style={this.state.selectValue === DataType.SELECT ? {} : { display: 'none' }}
                                                    rules={[{ required: true, message: '选项不可为空' }]}
                                                    {...this.tailLayout}
                                                >
                                                    <Button
                                                        type="dashed"
                                                        onClick={() => {
                                                            add();
                                                            this.setState({
                                                                ...this.state,
                                                                optionNumber: this.state.optionNumber + 1
                                                            })
                                                        }}
                                                        style={{ width: '60%' }}
                                                    >
                                                        <PlusOutlined />新增选项
                                                    </Button>
                                                </Form.Item>

                                            </div>
                                        );
                                }}
                            </Form.List>

                            <Form.Item {...this.tailLayout}>
                                <Button type="primary" htmlType="submit" size="large">
                                    确认添加
                                    </Button>
                            </Form.Item>
                        </Form>
                    </Card>
                </Spin>
            </div>
        )
    }
}